package org.jslaughter.camera.plugin;

import org.jslaughter.event.eventtype.DamageEvent;
import org.jslaughter.event.eventtype.DamageListener;
import org.jslaughter.event.eventtype.ExplosionEvent;
import org.jslaughter.event.eventtype.ExplosionListener;
import org.newdawn.slick.geom.Vector2f;
import org.nvframe.camera.Camera;
import org.nvframe.camera.plugin.CameraPlugin;
import org.nvframe.entity.Entity;
import org.nvframe.event.EventService;
import org.nvframe.event.eventtype.UpdateEvent;
import org.nvframe.event.eventtype.UpdateListener;

public class SHMShakyCamEffect implements CameraPlugin, ExplosionListener, UpdateListener, DamageListener {
	
	private Camera camera;
	private Entity focusEntity;
	
	private boolean shaking = false;
	private int maxOffsetRange = 30;
	private float skakeTime = 0;
	private int offsetRange;
	private float shakeInterval = 0;
	
	public SHMShakyCamEffect(Entity focusEntity) {
		this.focusEntity = focusEntity;
	}
	
	public void setCamera(Camera camera) {
		this.camera = camera;
		
		EventService.getInstance().addEventListener(this);
	}


	@Override
	public void onExplosion(ExplosionEvent event) {
		if(event.getTarget() != focusEntity) 
			return;
		
		offsetRange = maxOffsetRange;
		shakeInterval = 0;
		shaking = true;
	}

	@Override
	public void damageReceived(DamageEvent event) {

	}
	
	@Override
	public void onUpdate(UpdateEvent event) {
		if (!shaking)
	        return;
		
		skakeTime += event.getDelta();
		shakeInterval += event.getDelta();
		
		Vector2f localPosition = camera.getLocalPosition();

		float cameraAX = (float) (offsetRange * Math.cos(100 * skakeTime / 2000));
		float cameraAY = (float) (offsetRange * Math.cos(100 * skakeTime / 2000));
		
		localPosition.x = cameraAX;
		localPosition.y = cameraAY;
		
	    camera.setLocalPosition(localPosition);
	    
	    if(shakeInterval > 10) {
	    	offsetRange--;
	    	shakeInterval = 0;
	    }
		
		if(offsetRange <= 0)
			shaking = false;
	}

}
